package com.example.im.ui.fragment

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.im.common.Enumerate
import com.example.im.R
import com.example.im.common.ImApplication
import com.example.im.entity.EventBusData
import com.example.im.ui.activity.RoomActivity
import com.example.im.ui.adapter.FriendRoomAdapter
import com.example.im.common.Constants
import com.example.im.entity.FriendOrRoom
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseFragment
import kotlinx.android.synthetic.main.fragment_friend_view_page.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class FriendRoomFragment : AbstractBaseFragment<BasePresenter<*>>(),
    FriendRoomAdapter.OnClickItemListener {

    var rooms = ArrayList<FriendOrRoom>()
    var adapter: FriendRoomAdapter? = null

    override val layoutId: Int
        get() = R.layout.fragment_friend_view_page

    override fun initView() {

        EventBus.getDefault().register(this)

        rooms.addAll(ImApplication.appDatabase().friendOrRoomDao().selectRooms())
        adapter = FriendRoomAdapter(activity!!, rooms)
        adapter!!.setOnItemClickListener(this)
        recycler_view.layoutManager = LinearLayoutManager(activity)
        recycler_view.adapter = adapter
    }

    override fun initPresenter() {

    }

    override fun initLazyLoad() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(eventBus: EventBusData<FriendOrRoom>) {
        if (eventBus.type == null ||
            eventBus.type != Enumerate.Handle.list_group
        ) {
            return
        }
        val friend = eventBus.data
            ?: return
        when (eventBus.action ?: return) {
            Enumerate.Action.list_add ->
                adapter!!.addDataItem(friend)
            Enumerate.Action.list_delete ->
                adapter!!.removeDataItem(friend)
            else -> {
            }
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

    override fun onClickItem(view: View, position: Int) {
        val intent = Intent(activity, RoomActivity::class.java)
        intent.putExtra(Constants.BUNDLE_T0_ROOM_MARK, Constants.BUNDLE_T0_ROOM_MARK_CENTRE)
        intent.putExtra(Constants.BUNDLE_T0_ROOM_DATA, rooms[position])
        activity!!.startActivity(intent)
    }

}